<template>
  <div class="data-form user-form" v-loading.fullscreen.lock="loading">
    <template v-if="userForm!==null">
      <el-form label-width="auto" size="medium">
        <el-form-item label="用户名">
          <el-input v-if="type==='add'" v-model="userForm.username" class="form-input"></el-input>
          <span v-else>{{userForm.username}}</span>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="userForm.realName" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="总店">
          <span v-if="!userForm.hasAdmin">{{userForm.branchName}}</span>
          <el-select v-else filterable v-model="userForm.branchId" class="form-input" :disabled="partnerLoading" @change="branchChange">
            <el-option v-for="item in branchList" :key="item.id" :value="item.id" :label="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分店">
          <el-select clearable filterable v-model="userForm.partnerId" class="form-input" :disabled="partnerLoading">
            <el-option v-for="item in partnerList" :key="item.id" :value="item.id" :label="item.name" :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select filterable v-model="userForm.roleId" class="form-input" :disabled="partnerLoading">
            <el-option v-for="item in roleList" :key="item.id" :value="item.id" :label="item.name" :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="userForm.userPhone" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="userForm.status" class="form-input">
            <el-option v-for="item in statusList" :key="item.value" :value="item.value" :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div style="text-align:center">
        <el-button size="medium" type="primary" @click="saveUser">确定</el-button>
      </div>
    </template>
  </div>
</template>

<script>
  import UserForm from 'models/permission/userForm';

  import BranchApi from 'services/branchApi';
  import PermissionApi from 'services/permissionApi';

  export default {
    props: {
      user: {
        type: Object,
        required: true
      },
      userInfo: {
        type: Object,
        default () {
          return null;
        }
      },
      type: {
        type: String,
        default: 'add'
      },
      roles: {
        type: Array,
        required: true
      },
      dropdownOption: {
        type: Object,
        default () {
          return {};
        }
      }
    },

    data() {
      return {
        loading: false,
        partnerLoading: false,
        userForm: null,
        branchList: [],
        partnerList: [],
        roleList: [],
        statusList: this.i18n.getDropDown('user.status', [1, 0])
      };
    },

    created() {
      let type = this.type;
      let userForm;
      if (type === 'add') {
        userForm = new UserForm(this.user);
      } else {
        userForm = new UserForm(this.user, this.userInfo);
      }

      this.loading = true;
      Promise.all([
        this.setBranchList(userForm),
        this.setPartnerList(userForm, true),
        this.setRoleList(userForm, true)
      ]).then(() => {
        this.userForm = userForm;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    methods: {
      setBranchList(userForm) {
        if (!userForm.hasAdmin) {
          this.branchList = [];
          return Promise.resolve([]);
        }

        let dropdownOption = this.dropdownOption;
        let branchList = dropdownOption.branchList;
        if (branchList !== undefined) {
          this.branchList = branchList;
          return Promise.resolve(branchList);
        }

        return BranchApi.getBranchList().then(branchList => {
          this.branchList = branchList;
          dropdownOption.branchList = branchList;
          return branchList;
        });
      },

      setPartnerList(userForm, isInit = false) {
        let branchId = userForm.branchId;
        if (branchId === '') {
          this.partnerList = [];
          return Promise.resolve([]);
        }

        return PermissionApi.getPartners(branchId).then(partnerList => {
          if (isInit) {
            let partnerId = userForm.partnerId;
            if (partnerId !== '') {
              let obj = _.find(partnerList, {
                id: partnerId
              });
              if (obj === undefined) {
                partnerList.unshift({
                  id: partnerId,
                  name: userForm.partnerName,
                  disabled: true
                });
              }
            }
          } else {
            userForm.partnerId = '';
          }
          this.partnerList = partnerList;
          return partnerList;
        });
      },

      setRoleList(userForm, isInit = false) {
        let branchId = userForm.branchId;
        if (branchId === '') {
          this.roleList = [];
          return Promise.resolve([]);
        }

        let roleId = userForm.roleId;
        let roles = this.roles;
        let roleList = [];
        let flag = true;
        for (let i = 0; i < roles.length; i++) {
          let role = roles[i];
          if (role.branchId !== branchId) {
            continue;
          }

          let id = role.roleId;
          roleList.push({
            id: id,
            name: role.roleName
          });
          if (id === roleId) {
            flag = false;
          }
        }

        if (isInit) {
          if (flag && roleId !== '') {
            roleList.unshift({
              id: roleId,
              name: userForm.roleName,
              branchId: userForm.branchId,
              disabled: true
            });
          }
        } else {
          userForm.roleId = '';
        }

        this.roleList = roleList;
        return Promise.resolve(roleList);
      },

      branchChange() {
        this.partnerLoading = true;
        let userForm = this.userForm;
        Promise.all([
          this.setPartnerList(userForm),
          this.setRoleList(userForm)
        ]).then(() => {
          this.partnerLoading = false;
        }).catch(() => {
          this.partnerLoading = false;
        });
      },

      saveUser() {
        let userForm = this.userForm;
        let code = userForm.checkValid();
        if (code !== '') {
          let msg = this.i18n.getMsg(`user.error.${code}`);
          this.$message(msg);
          return;
        }

        if (this.type === 'add') {
          this.addUser(userForm);
        } else {
          this.updateUser(userForm);
        }
      },

      addUser(userForm) {
        this.loading = true;
        PermissionApi.addUserInfo(userForm).then(() => {
          this.loading = false;
          this.$alert('新增用户成功，默认登录密码为123456，为了您的账号安全请及时修改密码', '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      },

      updateUser(userForm) {
        this.loading = true;
        PermissionApi.updateUserInfo(userForm).then(() => {
          this.loading = false;
          this.$alert('修改用户成功', '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      }
    }
  };

</script>

<style lang="scss" scoped>
  @import '~viewStyle/dataForm';

</style>
